import React, { useState, useEffect } from 'react';
import { Table, Button, Radio, Row, Col, Input, Pagination, message } from 'antd';
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { imageList, ec2Hold, ec2Records } from '@/service';
import Cookies from 'js-cookie';
import { useTranslation } from 'react-i18next';
import ExampleConfirm from '@/components/ExampleConfirm';

export default (props) => {
    const [selectedRowKeys, setSelectedRowKeys] = useState('');
    const [inputValue, setInputValue] = useState('');
    const [exampleVisible, setExampleVisible] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();
    const token = Cookies.get("portal_token");
    const { t, i18n } = useTranslation();
    const initState = () => ({
        imgList: [],
        pageNo: 1,
        pageSize: 10,
        amiName: '',
        total: '',
        loading: false,
        btnLoading: false,
        containerList: [],

    }),
        [state, setState] = useState(initState),
        navigate = useNavigate(),
        dispatch = useDispatch();
    const columns = [
        { title: t('menu.home.table.imageId'), dataIndex: 'amiId', width: 200, ellipsis: true },
        { title: t('menu.home.table.imageName'), dataIndex: 'amiName', width: 200, ellipsis: true },
        { title: t('menu.home.table.system'), dataIndex: 'platform', width: 150 },
        {
            title: t('menu.home.table.architecture'),
            dataIndex: 'coreArchitecture',
            width: 150,
        },
        {
            title: t('menu.home.table.coreQuantity'),
            dataIndex: 'coreQuantity',
            width: 150,
        },
        {
            title: t('menu.home.table.coreCapacity'),
            dataIndex: 'coreCapacity',
            width: 150,
            render: (text) => `${text}G`,
        },
        {
            title: t('menu.home.table.reelType'),
            dataIndex: 'reelType',
            width: 150,
        },
        {
            title: t('menu.home.table.ebsCapacity'),
            dataIndex: 'ebsCapacity',
            width: 150,
            render: (text) => `${text}G`,
        },
        {
            title: t('menu.home.table.instanceType'),
            dataIndex: 'instanceType',
            width: 150,
        },
        {
            title: t('menu.home.table.pleaseChoose'),
            key: 'action',
            width: 150,
            fixed: 'right',
            // render: (_, record) => (
            //     <Radio
            //         checked={selectedRowKeys.includes(record.id.toString())}
            //         onChange={() => {
            //             if (selectedRowKeys.includes(record.id.toString())) {
            //                 setSelectedRowKeys(selectedRowKeys.filter(key => key !== record.id.toString()));
            //             } else {
            //                 setSelectedRowKeys([...selectedRowKeys, record.id.toString()]);
            //             }
            //         }}
            //     />
            // )
            render: (_, record) => (
                <Radio
                    disabled={record.state != 0}
                    checked={selectedRowKeys === record.id}
                    onChange={() => {
                        if (selectedRowKeys == record.id) {
                            setSelectedRowKeys('');
                        } else {
                            setSelectedRowKeys(record.id);
                        }
                    }}
                />
            )
        },
    ];
    const getList = () => {
        let params = {
            pageNo: 1,
            pageSize: 9999
        }
        ec2Records(params).then(res => {
            if (res.code == 0) {
                setState(o => ({
                    ...o,
                    containerList: res?.data?.records || [],
                }));
            }
        })
    }
    const confirm = () => {
        if (selectedRowKeys != '') {
            const instances = state.containerList;
            const hasSpecificStates = instances.some(instance =>
                [0, 1, 2, 3].includes(instance.state)
            );
            if (hasSpecificStates) {
                setExampleVisible(true);
            } else {
                goInstanceFn();
            }
        } else {
            messageApi.open({
                type:'warning',
                content:t('menu.home.check.image')
            })
        }
    }
    const goInstanceFn = () => {
        let params = {
            amiDbId: selectedRowKeys
        }
        setState(prevState => ({ ...prevState, btnLoading: true }));
        ec2Hold(params).then(res => {
            if (res.code == 0) {
                messageApi.open({
                    type: 'success',
                    content: res?.message,
                });
                setSelectedRowKeys('');
                setState(prevState => ({ ...prevState, btnLoading: false }));
                setTimeout(() => {
                    navigate('/instance');
                }, 1000);
            } else {
                messageApi.open({
                    type: 'error',
                    content: res?.message,
                });
                setState(prevState => ({ ...prevState, btnLoading: false }));
            }
        }).catch(e => {
            messageApi.open({
                type: 'error',
                content: e?.message,
            });
            setState(prevState => ({ ...prevState, btnLoading: false }));
        });
    }
    const handlePageChange = (page) => {
        setState(prevParams => ({ ...prevParams, pageNo: page }));
    };
    const handlePageSizeChange = (pageNo, pageSize) => {
        setState(prevParams => ({ ...prevParams, pageNo, pageSize }));
    };
    const immediateFn = () => {
        navigate('/login');
    }
    const onSearch = (value) => {
        setState(prevParams => ({ ...prevParams, amiName: value }));
    };
    const closeModalAndUpdate = () => {
        setExampleVisible(false);
        navigate('/instance');
        setSelectedRowKeys('');
    }
    const onInputChange = (e) => {
        const value = e.target.value;
        setInputValue(value);
        if (!value) {
            setState(prevParams => ({ ...prevParams, amiName: '' }));
        }
    };
    const getontainerList = () => {
        setState(prevState => ({ ...prevState, loading: true }));
        let params = {
            pageNo: state.pageNo,
            pageSize: state.pageSize,
            amiName: state.amiName
        }
        imageList(params).then(res => {
            if (res.code == 0) {
                setState(o => ({
                    ...o,
                    imgList: res?.data?.records || [],
                    total: res?.data?.total || 0,
                    loading: false
                }));
            } else {
                messageApi.open({
                    type: 'error',
                    content: res?.message,
                });
                setState(prevState => ({ ...prevState, loading: false }));
            }
        }).catch(e => {
            messageApi.open({
                type: 'error',
                content: e?.message,
            });
            setState(prevState => ({ ...prevState, loading: false }));
        });
    }
    useEffect(() => {
        if (token) {
            getList();
        }
    }, [i18n.language]);
    useEffect(() => {
        if (token) {
            getontainerList();
        }
    }, [state.pageNo, state.amiName, state.pageSize, i18n.language]);
    return (
        <div className={styles.container}>
            {token ? (<div className={styles.content}>
                <Row className={styles.titBlock}>
                    <Col span={12}>
                        <div className='custom-title'>{t('menu.home.title')}</div>
                    </Col>
                </Row>
                <Row className={styles.titBlock}>
                    <Col span={12}>
                        <div className={styles.inputWrapper}>
                            <span className={styles.label}>{t('menu.home.form.amiName')}</span>
                            <Input.Search value={inputValue} onChange={onInputChange} type="text" placeholder={t('common.modal.enterPlacehoder')} className='custom-input-search' style={{ width: '320px' }} onSearch={onSearch} enterButton />
                        </div>
                    </Col>
                    <Col span={12} style={{ textAlign: 'right' }}>
                        <Button type="primary" className="custom-btn-primary" onClick={confirm} loading={state.btnLoading}>
                            {t('menu.home.confirmBtn')}
                        </Button>
                    </Col>
                </Row>
                <Table
                    dataSource={state?.imgList}
                    columns={columns}
                    scroll={{ x: '100%' }}
                    pagination={false}
                    loading={state.loading} rowKey={'id'}
                    className='custom-table'
                />
                <div className='custom-Pagination'>
                    <Pagination
                        total={state?.total}
                        showSizeChanger
                        showQuickJumper
                        showTotal={(totalNum) => `${t('common.pagination.totalText')} ${totalNum} ${t('common.pagination.itemText')}`}
                        align="center"
                        current={state?.pageNo}
                        defaultPageSize={state?.pageSize}
                        onChange={handlePageChange}
                        onShowSizeChange={handlePageSizeChange}
                    />
                </div>
            </div>) : (<div className={styles.product}>
                <img src="/images/home1.png" className={styles.productImage} alt="" />
                <Button type="primary" className='custom-btn-primary' onClick={immediateFn}>{t('menu.home.useimmediately')}</Button>
            </div>)}
            <ExampleConfirm visible={exampleVisible} selectedRowKeys={selectedRowKeys} onClose={closeModalAndUpdate} />
            {contextHolder}

        </div>
    );
};
